import path from "path";
import fs from "fs";
import * as step from "@ali/flow-step-toolkit";

export async function setup(flowJobToken: string, mavenSettingXmlPath: string): Promise<void> {
    const mavenSettingXmlDir = path.dirname(mavenSettingXmlPath);
    fs.mkdirSync(mavenSettingXmlDir as string, {recursive: true})
    step.exportEnvVar('MAVEN_SETTING_XML_PATH', mavenSettingXmlPath)
    step.info(`export MAVEN_SETTING_XML_PATH=${mavenSettingXmlPath}`)

    const customMavenSettingCertificate = await step.certificate.getNewCustomMavenSettingCertificate(flowJobToken)
    if (!customMavenSettingCertificate ||                             //检查customMavenSettingCertificate是否是undefined或null
        !customMavenSettingCertificate.mavenSettingsContent ||        //检查mavenSettingsContent是否是undefined或null或空字符串 ""
        !customMavenSettingCertificate.mavenSettingsContent.trim()) { //检查mavenSettingsContent是否是仅包含空白字符的字符串
        step.info("custom maven settings is empty, use maven private repo settings")
    } else {
        fs.writeFileSync(mavenSettingXmlPath, customMavenSettingCertificate.mavenSettingsContent)
        step.info(`save customMavenSettingXml to ${mavenSettingXmlPath} successfully!`)
        return
    }

    const mavenPrivateRepoCertificate = await step.certificate.getNewMavenPrivateRepoCertificate(flowJobToken)
    if (!mavenPrivateRepoCertificate ||
        !mavenPrivateRepoCertificate.mavenSettingsContent ||
        !mavenPrivateRepoCertificate.mavenSettingsContent.trim()) {
        let message = "maven private repo settings is empty";
        throw new Error(message)
    }

    fs.writeFileSync(mavenSettingXmlPath, mavenPrivateRepoCertificate.mavenSettingsContent)
    step.info(`save mavenPrivateRepoCertificate to ${mavenSettingXmlPath} successfully!`)

    return
}